package com.example.yjh_login.jgServices;


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.yjh_login.R;
import com.tjf.lib_utils.LogsUtils;
import com.tjf.lib_utils.PxUtils;

import org.json.JSONObject;

import cn.jiguang.verifysdk.api.AuthPageEventListener;
import cn.jiguang.verifysdk.api.JVerificationInterface;
import cn.jiguang.verifysdk.api.JVerifyUIClickCallback;
import cn.jiguang.verifysdk.api.JVerifyUIConfig;
import cn.jiguang.verifysdk.api.PreLoginListener;
import cn.jiguang.verifysdk.api.RequestCallback;
import cn.jiguang.verifysdk.api.VerifyListener;
import tech.gujin.toast.ToastUtil;

/**
 * 极光一键登录
 */
public class JPushUtils {
    private Context context;

    public interface preAuthJpListener {
        void onAuthStatus(boolean isStart, int code, String msg);
    }

    public interface LoginAuthJpListener {
        void onAuthStatus(boolean isStart, int code, String msg);
    }

    public JPushUtils(Context context) {
        this.context = context;
    }

    boolean finishPrelogin = false;

    public void initJPush() {
        LogsUtils.i("极光登录的初始化====init ==");
        JVerificationInterface.setDebugMode(true);
        JVerificationInterface.init(context, 5000, new RequestCallback<String>() {
            @Override
            public void onResult(int i, String s) {
                if (i != 8000) {
                    ToastUtil.show(s);
                }
                LogsUtils.i("极光登录的初始化====init ==" + i + "=====" + s);
            }
        });
    }

    public boolean preAuth() {
        //判断SDK初始化状态
        if (JVerificationInterface.isInitSuccess()) {
            JVerificationInterface.preLogin(context, 5000, new PreLoginListener() {
                @Override
                public void onResult(final int code, final String content, JSONObject operatorReturn) {
                    //回调响应结果，建议用户增加一个字段存储预取号接口状态
                    LogsUtils.i("preAuth 预登录==", "[" + code + "]message=" + content, "operatorReturn=" + operatorReturn);
                    finishPrelogin = true;
                }
            });
        }
        return finishPrelogin;
    }

    public boolean preAuth(preAuthJpListener preAuthJpListener) {
        //判断SDK初始化状态
        if (JVerificationInterface.isInitSuccess()) {
            JVerificationInterface.preLogin(context, 5000, new PreLoginListener() {
                @Override
                public void onResult(final int code, final String content, JSONObject operatorReturn) {
                    //回调响应结果，建议用户增加一个字段存储预取号接口状态
                    LogsUtils.i("preAuth 预登录==", "[" + code + "]message=" + content, "operatorReturn=" + operatorReturn);
                    finishPrelogin = true;
                    if (preAuthJpListener != null) {
                        preAuthJpListener.onAuthStatus(true, 0, "成功");
                    }
                }
            });
        }
        return finishPrelogin;
    }

    public void loginAuth(boolean isDialogMode, LoginAuthJpListener loginAuthJpListener) {
        int result;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            result = context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            if (result != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(context, "[2016],msg = 当前缺少权限", Toast.LENGTH_SHORT).show();
                if (loginAuthJpListener != null) {
                    loginAuthJpListener.onAuthStatus(false, 600, "当前缺少权限");
                }
                return;
            }
        }

        boolean verifyEnable = JVerificationInterface.checkVerifyEnable(context);
        if (!verifyEnable) {
            if (loginAuthJpListener != null) {
                loginAuthJpListener.onAuthStatus(false, 601, "当前网络环境不支持认证");
            }
//            Toast.makeText(context, "[2016],msg = 当前网络环境不支持认证", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (!finishPrelogin) {
//            return;
//        }
        JVerificationInterface.clearPreLoginCache();
        //   showLoading();
        if (loginAuthJpListener != null) {
            loginAuthJpListener.onAuthStatus(true, 604, "开始授权");
        }
        setUIConfig(isDialogMode, loginAuthJpListener);
        //autoFinish 可以设置是否在点击登录的时候自动结束授权界面
        JVerificationInterface.loginAuth(context, true, new VerifyListener() {
            @Override
            public void onResult(final int code, final String content, final String operator, JSONObject operatorReturn) {
                LogsUtils.i("loginAuth==", "[" + code + "]message=" + content + ", " +
                        "operator=" + operator + ", operatorReturn=" + operatorReturn);
                if (loginAuthJpListener != null) {
                    loginAuthJpListener.onAuthStatus(false, code, content);
                }
            }
        }, new AuthPageEventListener() {
            @Override
            public void onEvent(int cmd, String msg) {
                LogsUtils.i("loginAuth==", "[onEvent]. [" + cmd + "]message=" + msg);

            }
        });
    }

    private void setUIConfig(boolean isDialogMode, LoginAuthJpListener loginAuthJpListener) {
        JVerifyUIConfig portrait = isDialogMode ? getDialogPortraitConfig() : getFullScreenPortraitConfig(loginAuthJpListener);

        //支持授权页设置横竖屏两套config，在授权页中触发横竖屏切换时，sdk自动选择对应的config加载。
        JVerificationInterface.setCustomUIWithConfig(portrait);
    }

    private JVerifyUIConfig getFullScreenPortraitConfig(LoginAuthJpListener loginAuthJpListener) {
        JVerifyUIConfig.Builder uiConfigBuilder = new JVerifyUIConfig.Builder();


        uiConfigBuilder.setNavColor(Color.WHITE);
        uiConfigBuilder.setStatusBarColorWithNav(true);
        uiConfigBuilder.setNavReturnImgPath("hd_title_back");
        uiConfigBuilder.setNavReturnBtnHeight(20);
        uiConfigBuilder.setNavReturnBtnWidth(20);
        uiConfigBuilder.setLogoOffsetY(43);
        uiConfigBuilder.setSloganOffsetY(300);
        uiConfigBuilder.setNumFieldOffsetY(260);
        uiConfigBuilder.setLogBtnOffsetY(380);
        uiConfigBuilder.setNumberSize(22);
        uiConfigBuilder.setSloganTextSize(18);
        uiConfigBuilder.setPrivacyState(true);
        uiConfigBuilder.setLogoImgPath("hd_login_content_icon");
        uiConfigBuilder.setLogoWidth(PxUtils.dp2px(context, 80.0f));
        uiConfigBuilder.setLogoHeight(PxUtils.dp2px(context, 80.0f));
        uiConfigBuilder.setLogBtnText("一键登录");
        uiConfigBuilder.setLogBtnTextSize(16);
        uiConfigBuilder.setLogBtnTextBold(true);
        uiConfigBuilder.setLogBtnWidth(300);
        uiConfigBuilder.setLogBtnHeight(54);
        uiConfigBuilder.setLogBtnImgPath("hd_shape_page_button_zise_juxing");

        uiConfigBuilder.setPrivacyText("登录即同意", "并授权宇宙熊获取本机号码");
        uiConfigBuilder.setPrivacyTextCenterGravity(true);
        uiConfigBuilder.setPrivacyTextSize(10);


        TextView mBtn = new TextView(context);
        mBtn.setText("其他手机号登录");
        mBtn.setGravity(Gravity.CENTER);
        mBtn.setTextSize(16);
        mBtn.setWidth(PxUtils.dp2px(context, 300.0f));
        mBtn.setHeight(PxUtils.dp2px(context, 54.0f));
        mBtn.setBackgroundResource(R.drawable.hd_shape_page_btn_grey_juxing);
        RelativeLayout.LayoutParams mLayoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams1.setMargins(PxUtils.dp2px(context, 54.0f), PxUtils.dp2px(context, 460.0f), 0, 0);

        mBtn.setLayoutParams(mLayoutParams1);
        uiConfigBuilder.addCustomView(mBtn, true, new JVerifyUIClickCallback() {
            @Override
            public void onClicked(Context context, View view) {
//                Toast.makeText(context, "动态注册的其他按钮", Toast.LENGTH_SHORT).show();
                if (loginAuthJpListener != null) {
                    loginAuthJpListener.onAuthStatus(false, 603, "其他手机号登录");
                }
            }
        });

        return uiConfigBuilder.build();
    }


    private JVerifyUIConfig getDialogPortraitConfig() {
        int widthDp = PxUtils.px2dp(context, PxUtils.getScreenWidth(context));
        LogsUtils.i("widthDp===" + widthDp);
        JVerifyUIConfig.Builder uiConfigBuilder = new JVerifyUIConfig.Builder()
                .setDialogTheme(widthDp - 30, 340, 0, 0, false);
//        uiConfigBuilder.setLogoHeight(30);
//        uiConfigBuilder.setLogoWidth(30);
//        uiConfigBuilder.setLogoOffsetY(-15);
//        uiConfigBuilder.setLogoOffsetX((widthDp-40)/2-15-20);
//        uiConfigBuilder.setLogoImgPath("logo_login_land");

        uiConfigBuilder.setLogoHidden(true);
        uiConfigBuilder.setNumFieldOffsetY(124).setNumberColor(Color.BLACK);
        uiConfigBuilder.setSloganOffsetY(165);
        uiConfigBuilder.setSloganTextColor(0xFFD0D0D9);
        uiConfigBuilder.setLogBtnOffsetY(221);
        uiConfigBuilder.setNumberSize(22);
        uiConfigBuilder.setSloganTextSize(18);
        uiConfigBuilder.setPrivacyOffsetY(15);
        uiConfigBuilder.setCheckedImgPath("jverification_demo_cb_chosen");
        uiConfigBuilder.setUncheckedImgPath("jverification_demo_cb_unchosen");
        uiConfigBuilder.setNumberColor(0xFF222328);
        uiConfigBuilder.setLogBtnImgPath("jverification_demo_selector_btn_main");
        uiConfigBuilder.setPrivacyState(true);
        uiConfigBuilder.setLogBtnText("一键登录");
        uiConfigBuilder.setLogBtnTextBold(true);
        uiConfigBuilder.setLogBtnHeight(40);
        uiConfigBuilder.setLogBtnImgPath("hd_shape_page_button_zise");

        uiConfigBuilder.setAppPrivacyColor(0xFFBBBCC5, 0xFF8998FF);
        uiConfigBuilder.setPrivacyText("登录即同意", "并授权宇宙熊获取本机号码");
        uiConfigBuilder.setPrivacyWithBookTitleMark(true);
        uiConfigBuilder.setPrivacyCheckboxHidden(true);
        uiConfigBuilder.setPrivacyTextCenterGravity(true);
        uiConfigBuilder.setPrivacyTextSize(10);


        // 图标和标题
        LinearLayout layoutTitle = new LinearLayout(context);
        RelativeLayout.LayoutParams layoutTitleParam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutTitleParam.setMargins(0, PxUtils.dp2px(context, 50), 0, 0);
        layoutTitleParam.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        layoutTitleParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutTitleParam.setLayoutDirection(LinearLayout.HORIZONTAL);
        layoutTitle.setLayoutParams(layoutTitleParam);

        ImageView img = new ImageView(context);
        img.setImageResource(R.mipmap.ic_launcher);
        TextView tvTitle = new TextView(context);
        tvTitle.setText("宇宙熊认证");
        tvTitle.setTextSize(18);
        tvTitle.setTextColor(Color.BLACK);
        tvTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

        LinearLayout.LayoutParams imgParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        imgParam.setMargins(0, 0, PxUtils.dp2px(context, 6), 0);
        LinearLayout.LayoutParams titleParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        imgParam.setMargins(0, 0, PxUtils.dp2px(context, 4), 0);

        layoutTitle.addView(img, imgParam);
        layoutTitle.addView(tvTitle, titleParam);
        layoutTitle.setGravity(Gravity.CENTER);
        uiConfigBuilder.addCustomView(layoutTitle, false, null);

        // 关闭按钮
        ImageView closeButton = new ImageView(context);

        RelativeLayout.LayoutParams mLayoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLayoutParams1.setMargins(0, PxUtils.dp2px(context, 10.0f), PxUtils.dp2px(context, 10), 0);
        mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        closeButton.setLayoutParams(mLayoutParams1);
        closeButton.setImageResource(R.drawable.hd_pop_close_icon);
        uiConfigBuilder.addCustomView(closeButton, true, null);
        return uiConfigBuilder.build();
    }


}
